package com.biejiaogroup.librarymanager.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("image/jpg;charset=utf-8");
        String fileName = request.getParameter("fileName");
        String filePath = "/src/headshots/" + fileName;

        response.addHeader("Content-Type","application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        InputStream in = new FileInputStream(new File(getServletContext().getRealPath(filePath)));
        ServletOutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }


    }
}
